package routers

import (
	"context"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/route"
	"hertz/api"
	myUtils "hertz/utils"
)

func loadUser(h *route.RouterGroup) {
	user := h.Group("/user")
	{
		user.GET("/", getUserInfo)
		user.POST("/register/", registerUser)
		user.POST("/login/", loginUser)
	}
}

func getUserInfo(c context.Context, ctx *app.RequestContext) {
	userAction := myUtils.GetParamUser(ctx)

	// 鉴权
	user, err := userProvider.Authenticate(c, &api.Token{
		Token:     userAction.Token,
		Operation: "GET_USER_INFO",
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	find, err := userProvider.Find(c, &api.User{
		Id: user.Id,
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	OK(ctx, utils.H{"user": transUser(find, find)})
}

func registerUser(c context.Context, ctx *app.RequestContext) {
	userAction := myUtils.GetParamUser(ctx)

	// 不鉴权

	token, err := userProvider.Register(c, &api.User{
		Username: userAction.Username,
		Password: userAction.Password,
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	OK(ctx, utils.H{"token": token.GetToken(), "user_id": token.GetId()})
}

func loginUser(c context.Context, ctx *app.RequestContext) {
	userAction := myUtils.GetParamUser(ctx)

	// 不鉴权

	token, err := userProvider.Login(c, &api.User{
		Username: userAction.Username,
		Password: userAction.Password,
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	OK(ctx, utils.H{"token": token.GetToken(), "user_id": token.GetId()})
}
